<template>
  <view class="detail-container">
    <!-- 标题 -->
    <!-- <view class="title">{{ title }}</view> -->
    <!-- 充电桩 -->
    <view class="scroll-item" :key="pile?.EquipmentID">
      <view class="pile-status-wrapper">
        <view
          :class="
            pile.ConnectorInfos?.[0].Status !== '空闲'
              ? 'pile-status--active'
              : ''
          "
          class="pile-status"
        >
          {{ pile?.ConnectorInfos?.[0]?.Status === "空闲" ? "空闲" : "已插枪" }}
        </view>
        <!-- <view class="time-info" v-if="pile?.status === 1">13:04插枪</view> -->
      </view>

      <view class="pile-rect">
        <view class="plie-header">
          <view class="pile-title">
            <text class="name">
              {{ pile?.EquipmentName || "" }}
            </text>
            <text class="code" v-if="false">
              ({{ pile?.EquipmentID || "" }})
            </text>
          </view>
          <view
            class="pile-type"
            :class="
              pile?.ConnectorInfos?.[0]?.ConnectorType === 3
                ? 'pile-type-slow'
                : ''
            "
          >
            {{ pile?.ConnectorInfos?.[0]?.ConnectorSpeed?.slice(0, 1) }}
          </view>
        </view>

        <view class="pile-car-info">
          <text class="text">终端编号 </text>
          <text class="text">{{ pile.EquipmentID }}</text>
        </view>
        <view class="pile-type-info">
          <text>
            {{ pile?.EquipmentType === 1 ? "直流快充" : "交流单相7kW" }} |
            国标2011 国标2015
          </text>
        </view>
      </view>
    </view>
    <!-- 价格 -->
    <view class="price-part">
      <view class="title">价格信息</view>
      <PriceInfo></PriceInfo>
    </view>
    <!-- 充电信息 -->
    <view
      class="price-part"
      v-if="pile?.ConnectorInfos?.[0]?.Status === '占用(充电中)'"
    >
      <view class="title">充电信息</view>
      <ChargeInfo :charge-info="chargeInfo"></ChargeInfo>
    </view>

    <!-- 操作按钮 -->
    <u-button
      v-if="pile?.ConnectorInfos?.[0]?.Status === '占用(充电中)'"
      type="error"
      class="btn-charge"
      shape="circle"
      :disabled="pile?.ConnectorInfos?.[0]?.Status !== '占用(充电中)'"
      @click="handleRemoteControl('stop')"
    >
      停止充电
    </u-button>
    <u-button
      v-else
      type="primary"
      class="btn-charge"
      shape="circle"
      :disabled="pile?.ConnectorInfos?.[0]?.Status !== '占用(未充电)'"
      @click="handleRemoteControl('in')"
    >
      立即充电
    </u-button>
    <u-toast ref="uToastRef"></u-toast>
  </view>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import {
  fetchTeldExplainSeq,
  fetchTeldEquipAuth,
  sendChargeCommand,
  fetchStopChargeSeq,
  sendStopChargeCommand,
  getPileDetail,
  getOrderListByOpenId,
} from "../../utils/api/teld";
import PriceInfo from "@/components/pirce-info/PriceInfo.vue";
import ChargeInfo from "@/components/charge-info/ChargeInfo.vue";
import usePileStore from "@/store/pile.js";

import useUserStore from "../../store/user";
const pileStore = usePileStore();
const userStore = useUserStore();
const uToastRef = ref(null);
const socket = ref(null);
const chargeInfo = ref({});
const pile = computed(() => {
  return pileStore.currentPile;
});

onLoad((options) => {
  console.log("options:", options);
  // console.log("pile:", pile);

  if (options.id) {
    // 根据 id 获取商品详情数据
    fetchDetailData(options.id);
  }
});

const initWebSocket = () => {
  socket.value = uni.connectSocket({
    // url: `ws://10.212.80.83:8082/websocket/${userStore.openid}/${pile.value.EquipmentID}`,
    url: `wss://backend-system-cluster01.ems.tckdq.com/websocket/${userStore.openid}/${pile.value.EquipmentID}`,
    complete: () => {},
  });
  // socket.value.onOpen(() => {
  //   console.log("WebSocket 连接已打开！");
  //   this.sendMessage("Hello, WebSocket!");
  // });

  socket.value.onMessage((message) => {
    const data = JSON.parse(message.data);
    console.log("data:", data);

    if (data.connectStatus === "connect") {
      console.log("连接成功！");
      // 只在第一次连接成功时发送一次消息
      socket.value.send({
        data: JSON.stringify({
          ConnectorID: pile.value.EquipmentID,
          Status: pile.value?.ConnectorInfos?.[0]?.Status,
        }),
        success: () => {
          console.log("消息发送成功！");
        },
      });
    }
    if (data.connectStatus === "data") {
      const chargeData = data.chargeMessage;
      chargeInfo.value = chargeData;
    }
    if (data.connectStatus === "change") {
      socket.value.send({
        data: JSON.stringify({
          ConnectorID: data.chargeMessage.ConnectorID,
          Status: data.chargeMessage.Status,
        }),
        success: () => {
          console.log("消息发送成功！");
        },
      });

      fetchDetailData(pile.value.EquipmentID).then(() => {
        wx.hideLoading();
      });
    }
    // if (data.connectStatus === "disconnect") {
    //   console.log("连接断开！");
    //   return;
    // }
  });

  socket.value.onError((error) => {
    console.error("WebSocket 连接失败:", error);
    wx.hideLoading();
  });

  socket.value.onClose(() => {
    console.log("WebSocket 连接已关闭！");
    wx.hideLoading();
  });
};

const closeSocket = () => {
  setTimeout(() => {
    socket?.value?.close({
      success: () => {
        console.log("前端调用 ---> WebSocket 关闭方法！");
      },
    });
  }, 100);
};
onMounted(() => {
  initWebSocket();
});
onUnmounted(() => {
  closeSocket();
});
/**
 * 获取桩详情
 * @param id
 */
const fetchDetailData = (id) => {
  const data = {
    StationsInfo: {
      LastQueryTime: "",
      PageNo: 1,
      PageSize: 50,
    },
    StationStatus: {
      StationIDs: ["5101161213"],
    },
    //想要查询的桩编号
    ConnectorID: id,
  };
  return getPileDetail(data).then((res) => {
    // console.log("res-detail:", res);
    pileStore.updatePile(res);
    return true;
  });
};
/**
 * 远程控制函数
 * @param type
 */
const handleRemoteControl = async (type) => {
  let hasUnPayOrder;
  try {
    const data = {
      openId: userStore.openid,
      payStatus: "", //整形数字，0：未支付， 1：已支付，全部查询填：null
    };
    getOrderListByOpenId(data).then((res) => {
      hasUnPayOrder = res.filter((item) => item.payStatus === 0).length;
      if (hasUnPayOrder) {
        uToastRef.value.show({
          type: "error",
          icon: true,
          title: "支付失败",
          message: "当前含有未支付订单，请支付后进行充电操作",
          duration: 3000,
          complete() {
            uni.navigateBack();
          },
        });
      } else {
        try {
          if (type === "in") {
            handleStartCharge();
          } else if (type === "stop") {
            handleStopCharge();
          }
        } catch (error) {
          console.log("error:", error);
        }
      }
    });
  } catch (error) {
    console.log("error:", error);
  }
};

// 充电相关流程
const handleStartCharge = async () => {
  try {
    const seq = await fetchTeldExplainSeq();
    const authData = {
      EquipAuthSeq: seq,
      ConnectorID: pile.value.EquipmentID,
    };
    const authRes = await fetchTeldEquipAuth(authData);
    if (authRes.SuccStat === 0) {
      const data = {
        StartChargeSeq: seq,
        ConnectorID: pile.value.EquipmentID,
        QRCode: "QRCode",
        PhoneNum: "13888888888",
        chargeType: 1,
        openId: userStore.openid,
        StationName: pile.value?.ConnectorInfos[0].StationName,
        ConnectorName: pile.value?.ConnectorInfos[0].ConnectorName,
      };
      const res = await sendChargeCommand(data);
      console.log("res-charge-command:", res);
      if (res.SuccStat === 0) {
        // uni.showToast({
        //   title: "已成功开始充电",
        //   duration: 2000,
        // });
        wx.showLoading({
          title: "启动中,请稍后",
        });
      } else {
        uni.showToast({
          title: "充电失败",
          icon: "error",
          duration: 2000,
        });
      }
    } else {
      uni.showToast({
        title: "充电授权失败",
        icon: "error",
        duration: 2000,
      });
    }
  } catch (error) {
    console.log("error:", error);
  }
};
// 停止充电相关流程
const handleStopCharge = async () => {
  try {
    console.log("pile:", pile);

    const res = await fetchStopChargeSeq({
      ConnectorID: pile.value.EquipmentID,
    });
    console.log("stop-seq:", res.StartChargeSeq);
    if (!res.StartChargeSeq) {
      uni.showToast({
        title: "停止充电失败",
        icon: "error",
        duration: 2000,
      });
      fetchDetailData(pile.value.EquipmentID);
      return;
    }
    const data = {
      StartChargeSeq: res.StartChargeSeq,
      ConnectorID: pile.value.EquipmentID,
      chargeType: 1, // 类型选择：1: APP , 2: PC
      openId: userStore.openid, // chargeType为1时必填!
    };
    const info = await sendStopChargeCommand(data);
    console.log("info:", info);

    if (info.SuccStat === 0) {
      uni.showToast({
        title: "已成功停止充电",
        duration: 2000,
      });
    } else {
      uni.showToast({
        title: "停止充电失败",
        duration: 2000,
        icon: "error",
      });
    }
    if (info?.data?.code === 500) {
      uToastRef.value.show({
        type: "error",
        icon: true,
        title: "",
        message: info.data.msg,
        duration: 3000,
      });
    }
  } catch (error) {
    console.log("error:", error);
    if (error?.data?.status === 400 || error?.data?.code === 500) {
      uni.showToast({
        title: "请求失败",
        duration: 2000,
        icon: "error",
      });
    }
  }
};
watch(
  () => pileStore.currentPile,
  (n) => {
    console.log("pile-data-change", n);
  }
);
</script>

<style lang="scss">
@import "../../style/common.scss";

.scroll-item {
  padding-left: 0;
  width: 100%;
}
.detail-container {
  box-sizing: border-box;
  padding: 12px 18px;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}
.price-part {
  width: 100%;
  margin-top: 12px;
  margin-bottom: 20px;
  // border: 1px solid #ccc;
  .title {
    font-size: 16px;
    font-weight: bold;
    color: $color-primary;
  }
}

.title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}

.btn-charge {
  margin-top: 20px;
}
</style>
